<template>
  <el-card shadow="never">
    <el-row style="margin-bottom: 20px" :gutter="20">
      <el-col :span="12">
        <el-form :inline="true" :model="listQuery" class="demo-form-inline">
          <el-form-item>
            <el-input v-model="listQuery.videoName" placeholder="视频名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="onQuery">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12">
        <el-row type="flex" justify="end">
          <el-upload
            style="display: inline-block; margin: 0 10px;"
            class="upload-demo"
            :action="uploadUrl"
            name="video"
            :show-file-list="false"
            accept="video/*"
            :before-upload="beforeUpload"
            :on-success="handleSuccess"
            :on-error="handleError"
          >
            <el-button type="primary" icon="el-icon-upload" :loading="uploading">点击上传</el-button>
          </el-upload>
          <!-- <el-tooltip class="item" effect="dark" content="只能上传mp4文件，且不超过5MB" placement="top-start">
            <i style="color: gray" class="el-icon-warning" />
          </el-tooltip> -->
          <el-button type="primary" icon="el-icon-warning" />
        </el-row>
      </el-col>
    </el-row>
    <el-row>
      <el-table v-loading="listLoading" :data="videos" border fit highlight-current-row style="width: 100%">
        <el-table-column width="80" align="center" label="ID">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column width="150" align="center" label="视频名称">
          <template slot-scope="scope">
            <span>{{ scope.row.video_name }}</span>
          </template>
        </el-table-column>

        <el-table-column width="150" align="center" label="状态">
          <template slot-scope="scope">
            <span>{{ scope.row.status | statusFilter }}</span>
          </template>
        </el-table-column>

        <el-table-column width="200" align="center" label="进度">
          <template slot-scope="scope">
            <el-progress :text-inside="true" :stroke-width="20" :percentage="scope.row.progress" status="exception" />
          </template>
        </el-table-column>

        <el-table-column width="100" align="center" label="伪造概率">
          <template slot-scope="scope">
            <span>{{ scope.row.probability | probabilityFilter }}</span>
          </template>
        </el-table-column>

        <el-table-column width="200" align="center" label="上传日期">
          <template slot-scope="scope">
            <span>{{ scope.row.create_date | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>

        <el-table-column min-width="150" align="center" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-data-analysis" @click="onDeepfakeDetection(scope.row)" />
            <el-button size="mini" icon="el-icon-view" @click="onViewVideo(scope.row.video_name, scope.row.status)" />
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="onRemoveVideo(scope.row.id)" />
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getVideos" />

      <el-dialog
        title="Deepfake视频检测"
        width="80%"
        :visible.sync="videoDialogVisible"
        @opened="videoDialogOpened()"
        @close="videoDialogClose()"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card>
              <video v-show="videoUrl" id="video1" ref="video" :key="videoUrl" width="100%">
                <source v-if="videoUrl" :src="videoUrl" type="video/mp4">
                Your browser does not support HTML video.
              </video>
              <el-empty v-show="!videoUrl" description="暂无数据" />
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <video v-show="maskVideoUrl" id="video1" ref="maskVideo" :key="videoUrl" width="100%">
                <source v-if="maskVideoUrl" :src="maskVideoUrl" type="video/mp4">
                Your browser does not support HTML video.
              </video>
              <el-empty v-show="!maskVideoUrl" description="暂无数据" />
            </el-card>
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px" type="flex" justify="center">
          <el-button style="font-size: 20px" :icon="btnIcon" round @click="switchPlay" />
        </el-row>
      </el-dialog>
    </el-row>
  </el-card>
</template>

<script>
import { fetchVideos, deleteVideo, runDeepfakeDetection, detectionProgress } from '@/api/deepfake'
import Pagination from '@/components/Pagination'

const BASE_API = process.env.VUE_APP_BASE_API
// const VIDEO_NAME = 'VIDEO_NAME'
// const MASK_NAME = 'MASK_NAME'

export default {
  name: 'Deepfake',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: '待检测',
        1: '正在检测',
        2: '完成检测',
        3: '执行失败'
      }
      return statusMap[status]
    },
    probabilityFilter(probability) {
      if (probability === 0.0) {
        return ''
      } else {
        return (probability * 100).toFixed(2) + '%'
      }
    }
  },
  data() {
    return {
      uploadUrl: BASE_API + '/deepfake/video',
      uploading: false,
      // fileList: [],
      videos: null,
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10,
        videoName: null
      },
      intervalId: null,
      videoDialogVisible: false,
      video: null,
      maskVideo: null,
      playing: false,
      btnIcon: 'el-icon-video-play',
      videoUrl: '',
      maskVideoUrl: ''
    }
  },
  created() {},
  mounted() {
    this.getVideos()
  },
  beforeDestroy() {},
  methods: {
    getVideos() {
      this.listLoading = true
      fetchVideos(this.listQuery).then(res => {
        // console.log(res)
        this.total = res.data._meta.total_items
        this.videos = res.data.items
        this.listLoading = false
      }).catch(error => {
        this.$message.error(error.message)
        this.listLoading = false
      })
    },
    onQuery() {
      this.getVideos()
    },
    beforeUpload(file) {
      const isVideo = (file.type === 'video/mp4' || file.type === 'video/x-msvideo')
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isVideo) {
        this.$message.error('请上传视频文件!')
      }
      if (!isLt5M) {
        this.$message.error('上传视频大小不能超过 5MB!')
      }
      return isVideo && isLt5M
    },
    handleSuccess(response, file) {
      // console.log(response.data, file)
      if (response.status_code >= 400) {
        this.$message.error(response.message)
      } else {
        this.$message.success('Success!!!')
        this.getVideos()
      }
    },
    handleError(response, file) {
      // console.log(response)
      this.uploading = false
      this.$message.error(response)
    },
    onDeepfakeDetection(videoObj) {
      // console.log(videoObj)
      if (this.intervalId) {
        clearInterval(this.intervalId)
      }
      if (videoObj.status !== 1) {
        videoObj.status = 1
        videoObj.progress = 0
      }
      const intervalTime = 2000
      const self = this
      runDeepfakeDetection(videoObj.id).then(res => {
        self.intervalId = setInterval(() => {
          detectionProgress(videoObj.id).then(res2 => {
            // console.log(res2)
            if (res2.data) {
              videoObj.status = res2.data.status
              videoObj.progress = res2.data.progress
              videoObj.probability = res2.data.probability
            }
            if (videoObj.status === 2) {
              clearInterval(self.intervalId)
            }
          }).catch(error2 => {
            clearInterval(self.intervalId)
          })
        }, intervalTime)
      }).catch(error => {
        // console.log(error)
        this.$message.error(error.message)
        self.intervalId = setInterval(() => {
          detectionProgress(videoObj.id).then(res2 => {
            // console.log(res2)
            videoObj.status = res2.data.status
            videoObj.progress = res2.data.progress
            videoObj.probability = res2.data.probability
            if (videoObj.status === 2) {
              clearInterval(self.intervalId)
            }
          }).catch(error2 => {
            clearInterval(self.intervalId)
          })
        }, intervalTime)
      })
    },
    onViewVideo(videoName, status) {
      this.videoUrl = BASE_API + '/deepfake/video/' + videoName
      // console.log(status)
      if (status === 2) {
        this.maskVideoUrl = BASE_API + '/deepfake/video/' + `${videoName.slice(0, -4)}_mask.webm`
      }
      this.videoDialogVisible = true
    },
    onRemoveVideo(videoId) {
      this.$confirm('此操作将永久删除该数据, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteVideo(videoId).then(res => {
          this.getVideos()
        }).catch(error => {
          this.$message.error(error.message)
          this.listLoading = false
        })
      })
    },
    videoDialogOpened() {
      this.video = this.$refs['video']
      this.maskVideo = this.$refs['maskVideo']
      // console.log(this.video, this.maskVideo)
    },
    videoDialogClose() {
      this.playing = false
      this.btnIcon = 'el-icon-video-play'
      this.videoUrl = null
      this.maskVideoUrl = null
      this.video.pause()
      if (this.maskVideoUrl) {
        this.maskVideo.pause()
      }
    },
    switchPlay() {
      if (!this.playing) {
        this.playing = true
        // this.setUpPage()
        this.btnIcon = 'el-icon-video-pause'
        this.video.play()
        if (this.maskVideoUrl) {
          this.maskVideo.play()
        }
      } else {
        this.playing = false
        // this.tearDownCamera()
        this.btnIcon = 'el-icon-video-play'
        this.video.pause()
        if (this.maskVideoUrl) {
          this.maskVideo.pause()
        }
      }
    }
  }
}
</script>
